<template>
  <div>
    <!-- 登录表单（未登录时显示） -->
    <div v-if="!isLoggedIn" class="login-container">
      <h2>用户登录</h2>
      <div class="form-group">
        <input v-model="loginForm.username" placeholder="用户名" />
      </div>
      <div class="form-group">
        <input v-model="loginForm.password" type="password" placeholder="密码" />
      </div>
      <button @click="login" :disabled="isLoading">
        {{ isLoading ? '登录中...' : '登录' }}
      </button>
      <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
    </div>

    <!-- 登录后管理界面 -->
    <div v-else class="management-container">
      <div class="header">
        <h2>用户管理</h2>
        <button @click="logout" class="logout-btn">退出登录</button>
      </div>

      <!-- 创建用户表单 -->
      <div class="section">
        <h3>创建用户</h3>
        <div class="form-group">
          <input v-model="newUser.username" placeholder="用户名（3-20位字母数字下划线）" />
        </div>
        <div class="form-group">
          <input v-model="newUser.password" type="password" placeholder="密码（8-20位，含字母+数字）" />
        </div>
        <button @click="createUser" :disabled="isLoading">
          {{ isLoading ? '创建中...' : '创建' }}
        </button>
      </div>

      <!-- 修改密码表单 -->
      <div class="section">
        <h3>修改密码</h3>
        <div class="form-group">
          <input v-model="changePasswordForm.username" placeholder="目标用户名" />
        </div>
        <div class="form-group">
          <input v-model="changePasswordForm.oldPassword" type="password" placeholder="原密码" />
        </div>
        <div class="form-group">
          <input v-model="changePasswordForm.newPassword" type="password" placeholder="新密码（8-20位，含字母+数字）" />
        </div>
        <button @click="changePassword" :disabled="isLoading">
          {{ isLoading ? '修改中...' : '修改' }}
        </button>
      </div>

      <!-- 删除用户表单 -->
      <div class="section">
        <h3>删除用户</h3>
        <div class="form-group">
          <input v-model="deleteUsername" placeholder="要删除的用户名" />
        </div>
        <button @click="deleteUser" :disabled="isLoading">
          {{ isLoading ? '删除中...' : '删除' }}
        </button>
      </div>

      <!-- 用户列表 -->
      <div class="section">
        <h3>用户列表</h3>
        <button @click="getAllUsers" :disabled="isLoading">
          {{ isLoading ? '刷新中...' : '刷新列表' }}
        </button>
        <ul v-if="users.length">
          <li v-for="user in users" :key="user.id" class="user-item">
            用户名: {{ user.username }} | ID: {{ user.id }}
          </li>
        </ul>
        <p v-else class="empty-tip">暂无用户数据</p>
      </div>
    </div>
  </div>
</template>

<script>
import { 
  login as apiLogin, 
  createUser as apiCreateUser, 
  deleteUser as apiDeleteUser, 
  getAllUsers as apiGetAllUsers,
  changePassword as apiChangePassword
} from '@/router/api'; 

export default {
  data() {
    return {
      isLoggedIn: !!localStorage.getItem('token'),  // 从localStorage读取登录状态
      loginForm: { username: '', password: '' },
      newUser: { username: '', password: '' },
      changePasswordForm: { username: '', oldPassword: '', newPassword: '' },
      deleteUsername: '',
      users: [],
      errorMessage: '',
      isLoading: false
    };
  },
  mounted() {
    if (this.isLoggedIn) this.getAllUsers();  // 登录状态自动加载数据
  },
  methods: {
    async login() {
      this.isLoading = true;
      this.errorMessage = '';
      try {
        const res = await apiLogin(this.loginForm);
        console.log('登录响应:', res);  // 打印响应数据
        if (res.code === 200 && res.data.access_token) {  // 登录成功后加载用户列表
          localStorage.setItem('token', res.data.access_token);  // 存储JWT token
          this.isLoggedIn = true;  // 更新登录状态
          this.$router.push('/');  // 跳转到主页
        }
        else {
          this.errorMessage = res.message || '登录失败，请检查用户名密码';
        }
      } catch (err) {
        this.errorMessage = '网络异常，请稍后重试';
        // console.error('登录请求失败:', err);
      } finally {
        this.isLoading = false;
      }
    },
    async logout() {
      localStorage.removeItem('token');  // 清除token
      this.isLoggedIn = false;
      this.users = [];  // 清空用户数据
    },
    async createUser() {
      if (!this.validateUserForm(this.newUser)) return;  // 前端校验
      this.isLoading = true;
      try {
        const res = await apiCreateUser(this.newUser, localStorage.getItem('token'));  // 携带token
        alert(res.data.message);
        this.getAllUsers();  // 刷新列表
        this.newUser = { username: '', password: '' };  // 清空表单
      } catch (err) {
        console.error('创建用户失败:', err);
        alert(err.response?.data?.message || '创建用户失败');
      } finally {
        this.isLoading = false;
      }
    },
    async deleteUser() {
      if (!this.deleteUsername) {
        alert('请输入要删除的用户名');
        return;
      }
      this.isLoading = true;
      try {// 打印删除的用户名
        const res = await apiDeleteUser(this.deleteUsername, localStorage.getItem('token'));  // 携带token
        alert(res.data.message);
        this.getAllUsers();  // 刷新列表
        this.deleteUsername = '';  // 清空输入
      } catch (err) {
        console.error('删除用户失败:', err);
        alert(err.response?.data?.message || '删除用户失败');
      } finally {
        this.isLoading = false;
      }
    },
    async getAllUsers() {
      this.isLoading = true;
      try {
        console.log(localStorage.getItem('token'));  // 调试信息
        const res = await apiGetAllUsers(localStorage.getItem('token'));  // 携带token
        this.users = res.data.users;  // 假设后端返回users数组
      } catch (err) {
        console.error('获取用户列表失败:', err);
        if (err.response?.status === 401) {  // token失效
          this.logout();  // 自动退出登录
          alert('登录状态已过期，请重新登录');
        }
      } finally {
        this.isLoading = false;
      }
    },
    async changePassword() {
      if (!this.validatePasswordForm(this.changePasswordForm)) return;  // 前端校验
      this.isLoading = true;
      try {
        const res = await apiChangePassword(this.changePasswordForm, localStorage.getItem('token'));  // 携带token
        alert(res.data.message);
        this.changePasswordForm = { username: '', oldPassword: '', newPassword: '' };  // 清空表单
      } catch (err) {
        console.error('修改密码失败:', err);
        alert(err.response?.data?.message || '修改密码失败');
      } finally {
        this.isLoading = false;
      }
    },
    // 前端校验辅助方法
    validateUserForm(user) {
      if (!user.username || !user.password) {
        alert('用户名和密码不能为空');
        return false;
      }
      if (!/^[a-zA-Z0-9_]{3,20}$/.test(user.username)) {
        alert('用户名需为3-20位字母数字下划线');
        return false;
      }
      if (!/^(?=.*[a-zA-Z])(?=.*\d).{8,20}$/.test(user.password)) {
        alert('密码需8-20位，且包含字母和数字');
        return false;
      }
      return true;
    },
    validatePasswordForm(form) {
      if (!form.username || !form.oldPassword || !form.newPassword) {
        alert('所有字段不能为空');
        return false;
      }
      if (!/^(?=.*[a-zA-Z])(?=.*\d).{8,20}$/.test(form.newPassword)) {
        alert('新密码需8-20位，且包含字母和数字');
        return false;
      }
      return true;
    }
  }
};
</script>

<style scoped>
.login-container, .management-container {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
  box-shadow: 0 0 10px #eee;
}
.form-group {
  margin: 15px 0;
}
input {
  width: 100%;
  padding: 8px;
  margin: 5px 0;
  border: 1px solid #ddd;
  border-radius: 4px;
}
button {
  padding: 8px 15px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
button:disabled {
  background: #999;
  cursor: not-allowed;
}
.error-message {
  color: #dc3545;
  margin-top: 10px;
}
.section {
  margin: 20px 0;
  padding: 15px;
  border-top: 1px solid #eee;
}
.user-item {
  margin: 8px 0;
  padding: 5px;
  background: #f8f9fa;
  border-radius: 4px;
}
.empty-tip {
  color: #666;
  margin: 10px 0;
}
.logout-btn {
  margin-left: 20px;
  background: #dc3545;
}
</style>
